import Square from "@/components/Square";
import calculateWinner from "@/utils/helps";

interface BoardProps {
  squares: Array<string>;
  onPlay: (squares: Array<string>) => void;
  xIsNext: boolean;
}

export default function Board({ squares, onPlay, xIsNext }: BoardProps) {
  // 会在挂载和更新的时候变化
  const winner = calculateWinner(squares);
  
  let status;
  if (winner) {
    status = `Winner: ${winner}`;
  } else {
    status = "Next player: " + (xIsNext ? "X" : "O");
  }

  const handleClick = (index: number) => {
    // square已经走过了就直接返回,或者已经赢了也不继续
    if (squares[index] || calculateWinner(squares)) return;

    const nextSquares = squares.slice();
    nextSquares[index] = xIsNext ? "X" : "O";
    onPlay(nextSquares);
  };
  return (
    <>
      <p className="status">{status}</p>

      <div className="board-container">
        {squares.map((square,index)=><Square value={square} onSquareClick={() => handleClick(index)} />)}
      </div>
    </>
  );
}
